package admin

import (
	"context"
	"errors"
	"slices"
	"sort"
	"strings"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type PermissionListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPermissionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PermissionListLogic {
	return &PermissionListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PermissionListLogic) PermissionList(req *types.PermissionListReq) (resp []types.PermissionListResp, err error) {
	// 获取所有权限数据
	datas := make([]models.Permission, 0)
	tx := utils.Db.Model(&models.Permission{}).Order("sort ASC,id ASC")
	utils.TxFind(tx, &datas)
	if len(datas) == 0 {
		return []types.PermissionListResp{}, nil
	}
	logx.Infof("获取权限列表成功: %v", datas)
	roleActions := make([]string, 0)
	if req.RoleID > 0 {
		// 检查角色是否存在
		role := &models.AdminRole{}
		if !utils.GetDataById(req.RoleID, role) {
			logx.Errorf("角色不存在: %v", err)
			return nil, errors.New("角色不存在")
		}
		roleActions = strings.Split(role.Permissions.String(), ",")
	}

	// 构建权限树
	permissionMap := make(map[uint][]models.Permission)
	for _, p := range datas {
		// 检查该权限是否在角色对应的动作中
		if req.RoleID > 0 {
			if slices.Contains(roleActions, p.Perm) {
				permissionMap[p.ParentID] = append(permissionMap[p.ParentID], p)
			}
		} else {
			permissionMap[p.ParentID] = append(permissionMap[p.ParentID], p)
		}

	}

	// 生成树形结构
	var buildTree func(parentID uint) []types.PermissionListResp
	buildTree = func(parentID uint) []types.PermissionListResp {
		var nodes []types.PermissionListResp
		children, exists := permissionMap[parentID]
		if exists {
			// 按排序字段排序
			sort.Slice(children, func(i, j int) bool {
				return children[i].Sort < children[j].Sort
			})
			for _, child := range children {
				node := types.PermissionListResp{}
				copier.Copy(&node, child)
				children := buildTree(child.ID)
				if len(children) > 0 {
					node.Children = children
				} else {
					node.Children = []types.PermissionListResp{}
				}
				nodes = append(nodes, node)
			}
		}
		return nodes
	}

	// 从根节点开始构建树
	rootNodes := buildTree(0)

	return rootNodes, nil
}
